<?php
// +----------------------------------------------------------------------
// | Longbing [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright Chengdu longbing Technology Co., Ltd.
// +----------------------------------------------------------------------
// | Website http://longbing.org/
// +----------------------------------------------------------------------
// | Sales manager: +86-13558882532 / +86-13330887474
// | Technical support: +86-15680635005
// | After-sale service: +86-17361005938
// +----------------------------------------------------------------------

namespace app\shortvideo\model;

use app\BaseModel;
use app\shop\model\AdminGoods;
use app\shop\model\IndexGoods;
use think\facade\Db;

class Shortvideo extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_shortvideo';

    public $append = ['browse_count','send_count','video_vid'
    ];


    /**
     * @param $value
     * @param $data
     * @功能说明:腾讯视频
     * @author chenniang
     * @DataTime: 2020-05-22 18:38
     */
    public function getVideoVidAttr($value,$data){

        if(!empty($data['video'])){
            return lbGetTencentVideo($data['video']);
        }

    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/18 18:16
     * @功能说明: 统计浏览
     */
    public function getBrowseCountAttr($value,$data){
        $count = ShortvideoBrowse::where([
            'video_id'=>$data['id']
        ])->count();
        return $count;
    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/18 18:16
     * @功能说明:统计转发
     */
    public function getSendCountAttr($value,$data){
        $count = ShortvideoVisitors::where([
            'video_id' => $data['id'],
            'mode' => 4
        ])->count();
        return $count;
    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/18 17:50
     * @功能说明: 获取短视频列表
     */
    public function videoList($where = [],$page = 10){
        $query = $this->where($where)->where('status','<>','-1')->order('top desc,create_time desc');
        if($page){
            $query = $query->paginate($page);
        }else{
            $query = $query->select();
        }
        return !empty($query)?$query->toArray():[];
    }

    public function returnData($input){
        $data = [];
        $data['is_public']         = $input['all_company']?1:0; #是否公共视频 0：不是，1：是(所有公司)
        $data['status']            = isset($input['status'])?$input['status']:1;  #视频状态 0.不展示 1.展示
        $data['title']             = $input['title'];
        $data['cover']             = $input['cover'];
        $data['video']             = $input['video'];
        $data['describe']          = $input['describe'];
        $data['tel_num']           = isset($input['tel_num'])?$input['tel_num']:0;
        $data['wechat_num']        = isset($input['wechat_num'])?$input['wechat_num']:0;
        $data['send_num']          = isset($input['send_num'])?$input['send_num']:0;
        $data['goods_id']          = isset($input['goods_id'])?$input['goods_id']:0;
//        $data['preferential_id']   = isset($input['preferential_id'])?$input['preferential_id']:0; //已被废弃 转为表关联
//        $data['preferential_type'] = isset($input['preferential_type'])?$input['preferential_type']:0; //已被废弃 转为表关联
        $data['top']               = isset($input['top'])?$input['top']:0; #排序由大到小

        $data['limit_type']        = isset($input['limit_type'])?$input['limit_type']:0; #排序由大到小
//        $data['create_time']       = time();

        return $data;
    }
    /**
     **@param $data
     * @功能说明:
     * @author lichuanming
     * @DataTime: 2020/5/18 15:49
     */
    public function videoAdd($data){
        $data['create_time'] = time();
        $data['status']      = 1;
        $this->insert($data);
        $res = $this->getLastInsID();
        return $res;
    }

    public function videoUpdate($dis,$data){
        $data['update_time'] = time();
        $res = self::where($dis)->update($data);
        return $res;
    }


    /**
     **@author lichuanming
     * @DataTime: 2020/5/19 16:05
     * @功能说明: 获取员工列表 并按获客认数排序
     */
    public function staffUserList($where,$page = 10,$order = 'visitor_user',$by = 'desc'){
        $query = Db::name('longbing_card_user_info')->alias('a'); #定义查询 --

        $field = '';
        //将需要排序的字段单独使用子查询
        switch ($order){
            case 'visitor_user': //按获客人数排序
                $visitor_user_sql = Db::name('longbing_card_shortvideo_visitors')->field('count(distinct user_id)')->where([
                    ['staff_id' ,'=' ,'`a`.`fans_id`'],
                    ['video_id' ,'=' ,'`b`.`video_id`'],
                    ['type' ,'=' ,1],
                    ['first','=',1]
                ]);
                $field .= "{$visitor_user_sql->buildSql()} as visitor_user,";
                break;
            case 'browse_user': //按浏览人数
                $browse_user_sql = Db::name('longbing_card_shortvideo_browse')->field('count(distinct user_id)')->where([
                    ['staff_id' ,'=' ,'`a`.`fans_id`'],
                    ['video_id' ,'=' ,'`b`.`video_id`'],
                ]);

                $field .= "{$browse_user_sql->buildSql()} as browse_user,";
                break;
            case 'browse_time': //按浏览时长排序
                $browse_time_sql = Db::name('longbing_card_shortvideo_browse')->field('sum(browse_time)')
                    ->where([
                        'staff_id'=>'`a`.`fans_id`',
                        'video_id'=>'`b`.`video_id`',
                    ]);

                $field .= "{$browse_time_sql->buildSql()} as browse_time,";
                break;
            case 'send_user': //按转发人数排序
                $send_user_sql = Db::name('longbing_card_shortvideo_visitors')->field('count(distinct user_id)')->where([
                    ['staff_id' ,'=' ,'`a`.`fans_id`'],
                    ['video_id' ,'=' ,'`b`.`video_id`'],
                    ['mode' ,'=' ,4],
                ]);
                $field .= "{$send_user_sql->buildSql()} as send_user,";
                break;
        }
        $field .= 'a.avatar,a.name,a.fans_id,a.company_id,a.phone,g.nickName,b.video_id,';
        $field .= 'c.name as company_name,d.name as top_company_name,f.name as job_name,a.create_time';

        $list = $query->join('longbing_card_shortvideo_browse b','a.fans_id = b.staff_id')
            ->join('longbing_card_user g','a.fans_id = g.id')
            ->join('longbing_card_company c', 'a.company_id = c.id', 'LEFT' )
            ->join('longbing_card_company d', 'c.top_id = d.id', 'LEFT' )
            ->join('longbing_card_job f', 'f.id = a.job_id', 'LEFT' )
            ->where('a.is_staff','=',1) #查询员工
            ->where($where)
            ->field($field)
            ->group('a.fans_id')
            ->order($order.' '.$by.',a.create_time desc')
            ->paginate($page)
            ->toArray();

        //获取浏览人数
        foreach ($list['data'] as $key=>$val){
            if($val['company_name'] && !$val['top_company_name']){
                $list['data'][$key]['top_company_name'] = $val['company_name'];
                $list['data'][$key]['company_name'] = '未设置部门';
            }

            //如果员工的名称 或 头像不存在
            if(!$val['name'] || !$val['avatar']){
                $user_info = Db::name('longbing_card_user')->where('id','=',$val['fans_id'])->field('avatarUrl,nickName')->find();
                $list['data'][$key]['avatar'] = $val['avatar']?$val['avatar']:$user_info['avatarUrl'];
            }

            $list['data'][$key][$order] = $val[$order]?$val[$order]:0;
            if($order != 'visitor_user'){
                $visitor_user = Db::name('longbing_card_shortvideo_visitors')->field('count(id)')->where([
                    ['staff_id' ,'=' , $val['fans_id']],
                    ['video_id' ,'=' , $val['video_id']],
                    ['type' ,'=' ,1],
                    ['first','=',1]
                ])->group('user_id')->count();

                $list['data'][$key]['visitor_user'] = $visitor_user;
            }

            if($order != 'browse_user'){
                $browse_user = Db::name('longbing_card_shortvideo_browse')->field('count(id)')->where([
                    ['staff_id' ,'=' ,$val['fans_id']],
                    ['video_id' ,'=' , $val['video_id']],
                ])->group('user_id')->count();
                $list['data'][$key]['browse_user'] = $browse_user;
            }

            if($order != 'browse_time'){
                $browse_time = Db::name('longbing_card_shortvideo_browse')
                    ->field('sum(browse_time) as browse_time')
                    ->where([
                        'staff_id'=>$val['fans_id'],
                        'video_id'=>$val['video_id'],
                    ])->find();
                $list['data'][$key]['browse_time'] = $browse_time['browse_time'];
            }

            if($order != 'send_user'){
                $send_user = Db::name('longbing_card_shortvideo_visitors')->where([
                    ['staff_id' ,'=' , $val['fans_id']],
                    ['video_id' ,'=' , $val['video_id']],
                    ['mode','=',4]
                ])->group('user_id')->count();
                $list['data'][$key]['send_user']  = $send_user;
            }
        }
        $list['order'] = $order;
        $list['by'] = $by;
        return $list;
    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/19 17:30
     * @功能说明: 用户列表
     */
    public function userList($where,$page = 10,$order,$by){
        $field = '';
        //生成子查询
        switch ($order){
            case 'browse_time':#统计浏览时长
                $browse_time = Db::name('longbing_card_shortvideo_browse')->field('sum(browse_time)')
                    ->where([
                        'user_id'=>'`a`.`id`',
                        'video_id'=>'`b`.`video_id`',
                    ])
                    ->buildSql();
                $field .= "{$browse_time} as browse_time,";
                break;
            case 'send_count': #转发次数
                $send_count = Db::name('longbing_card_shortvideo_visitors')->field('count(id)')->where([
                    ['user_id' ,'=' ,'`a`.`id`'],
                    ['video_id' ,'=' ,'`b`.`video_id`'],
                    ['mode' ,'=' ,4],
                ])->buildSql();
                $field .= "{$send_count} as send_count,";
                break;
            case 'browse_count': #浏览次数
                $browse_count = Db::name('longbing_card_shortvideo_browse')->field('count(id)')->where([
                    ['user_id' ,'=' ,'`a`.`id`'],
                    ['video_id' ,'=' ,'`b`.`video_id`'],
                ])->buildSql();
                $field .= "{$browse_count} as browse_count,";
                break;
        }
        $field .= 'a.id,a.avatarUrl,a.nickName,c.phone,b.video_id';
        $list = Db::name('longbing_card_user')->alias('a')
            ->join('longbing_card_shortvideo_browse b','a.id = b.user_id')
            ->join('longbing_card_user_phone c','a.id = c.user_id','LEFT')
            ->where('a.is_staff','=',0)
            ->where($where)
            ->field($field)
            ->group('a.id')
            ->order($order.' '.$by.',a.create_time desc')
            ->paginate($page)
            ->toArray();

        foreach ($list['data'] as $key=>$val){
            $list['data'][$key][$order] = $val[$order]?$val[$order]:0;
            if($order != 'browse_time'){
                $browse_time =  Db::name('longbing_card_shortvideo_browse')->field('sum(browse_time) as browse_time')
                    ->where([
                        'user_id'=>$val['id'],
                        'video_id'=>$val['video_id'],
                    ])->find();
                $list['data'][$key]['browse_time'] = $browse_time['browse_time'];
            }

            if($order != 'send_count'){
                $send_count = Db::name('longbing_card_shortvideo_visitors')->where([
                    ['user_id' ,'=' , $val['id']],
                    ['video_id' ,'=' , $val['video_id']],
                    ['mode','=',4]
                ])->count();
                $list['data'][$key]['send_count'] = $send_count;
            }

            if($order != 'browse_count'){
                $browse_count = Db::name('longbing_card_shortvideo_browse')->where([
                    'user_id'=>$val['id'],
                    'video_id'=>$val['video_id']
                ])->count();

                $list['data'][$key]['browse_count'] = $browse_count;
            }
        }

        return $list;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-05-19 16:43
     * @功能说明:获取员工有权限的视频
     */
    public function getStaffVideo($dis,$staff_id){

        $company_id = Db::name('longbing_card_user_info')->where(['fans_id'=>$staff_id])->value('company_id');
        //选择了公司的
        $mapor[] = ['b.staff_id','=',$staff_id];

        $mapor[] = ['b.company_id','=',$company_id];
        //公共的
        $mapor[] = ['a.is_public','=',1];

        $data = $this->alias('a')
                ->join('longbing_card_shortvideo_company b','b.video_id = a.id','left')
                ->where($dis)
                ->where(function ($query) use ($mapor){
                    $query->whereOr($mapor);
                })
                ->column('a.id');

        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-05-19 09:46
     * @功能说明:前端短视频列表
     */
    public function indexVideoList($dis,$staff_id,$page=5){

        $company_id = Db::name('longbing_card_user_info')->where(['fans_id'=>$staff_id])->value('company_id');
        //选择了公司的
        $mapor[] = ['b.staff_id','=',$staff_id];

        $mapor[] = ['b.company_id','=',$company_id];
        //公共的
        $mapor[] = ['a.is_public','=',1];

        $data = $this->alias('a')
                ->join('longbing_card_shortvideo_company b','b.video_id = a.id ','left')
                ->where($dis)
                ->where(function ($query) use ($mapor){
                    $query->whereOr($mapor);
                })
                ->field('a.*')
                ->group('a.id')
                ->order('top desc,id desc')
                ->paginate($page)
                ->toArray();

        $staff = Db::name('longbing_card_user_info')->where(['fans_id'=>$staff_id])->field('fans_id,phone,wechat')->find();
        //员工头像
        $staff['staff_avatar'] = lbUserAvatar($staff_id);
        //公司名称
        $staff['company_name'] = lbUserCompany($staff_id);

        $data['staff_info']    = $staff;

        if(!empty($data['data'])){
            //统计模型
            $visitors_model = new ShortvideoVisitors();
            //商品模型
            $goods_model    = new ShortvideoGoods();
            //商城的商品模型
            $shop_goods_model = new IndexGoods();
            //优惠模型
            $prefer_model     = new ShortvideoPreferential();

            foreach ($data['data'] as &$v){

                $v_dis = [
                    //员工
                    'staff_id' => $staff_id,
                    //视频
                    'video_id' => $v['id'],
                    //只查用户
                    'type'     => 1,
                    //授权电话
                    'mode'     => 2,
                ];
                //该员工下面的这是授权电话数量
                $true_mobile   = $visitors_model->getCount($v_dis,'id');
                //复制微信
                $v_dis['mode'] = 3;
                //该员工下面的这是复制微信数量
                $true_wx       = $visitors_model->getCount($v_dis,'id');
                //复制微信
                $v_dis['mode'] = 4;
                //该员工下面的真实转发数量
                $true_send     = $visitors_model->getCount($v_dis,'id');
                //电话授权数量
                $v['tel_num'] += $true_mobile;
                //微信授权数量
                $v['wechat_num'] += $true_wx;
                //转发授权数量
                $v['send_num']   += $true_send;

                $goods = $goods_model->where(['video_id'=>$v['id']])->column('goods_id');
                //优惠列表
                $v['preferential'] = $prefer_model->where(['video_id'=>$v['id']])->where('preferential_id','>',0)->field('preferential_id,type')->select();
                //商品列表
                $v['goods_list'] = $shop_goods_model->where([['id','in',$goods]])->select();

            }

        }

        return $data;
    }




    /**
     * @author chenniang
     * @DataTime: 2020-05-19 09:46
     * @功能说明:员工端短视频列表
     */
    public function staffVideoList($dis,$staff_id,$status=2){
//
//         switch ($status){
//             //获客人数
//             case 1:
//                 $order = 'get_count';
//                 break;
//             case 2:
//             //浏览人数
//                 $order = 'browse_num';
//                 break;
//             //转发人数
//             case 3:
//                 $order = 'send_num';
//                 break;
//         }

        $company_id = Db::name('longbing_card_user_info')->where(['fans_id'=>$staff_id])->value('company_id');
        //选择了公司的
        $mapor[] = ['b.staff_id','=',$staff_id];

        $mapor[] = ['b.company_id','=',$company_id];
        //公共的
        $mapor[] = ['a.is_public','=',1];

        $data = $this->alias('a')
            ->join('longbing_card_shortvideo_company b','b.video_id = a.id','left')
//            ->join('longbing_card_user_info c','c.company_id = b.company_id','left')
//            ->join('longbing_card_shortvideo_visitors d','d.video_id = a.id AND d.type=1','left')
//            ->join('longbing_card_shortvideo_browse e','e.video_id = a.id AND e.type=1','left')
//            ->join('longbing_card_shortvideo_visitors f','f.video_id = a.id AND f.type=1 AND f.mode = 4','left')
            ->where($dis)
            ->where(function ($query) use ($mapor){
                $query->whereOr($mapor);
            })
            ->field(['a.cover','a.describe','a.title','a.id'])
            ->group('a.id')
            ->order(["id desc"])
            ->paginate(10)
            ->toArray();
        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $dis=[

                    'video_id' => $v['id'],

                    'type'     => 1
                ];
                //获客人数
                $v['get_count']  = Db::name('longbing_card_shortvideo_visitors')->where($dis)->count();
                //浏览人数
                $v['browse_num'] = Db::name('longbing_card_shortvideo_browse')->where($dis)->count();

                $dis['mode']     = 4;
                //转发人数
                $v['send_num']   = Db::name('longbing_card_shortvideo_visitors')->where($dis)->count();
                

            }
        }
        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-05-20 09:36
     * @功能说明:详情
     */
    public function videoInfo($dis,$field = '*'){

        $data = $this->where($dis)->field($field)->find();

        return !empty($data)?$data->toArray():[];

    }




}